package com.erb.controller.zwj.admin;

import com.alibaba.fastjson.JSONObject;
import com.erb.constants.AdminConstants;
import com.erb.entity.Admin;
import com.erb.entity.RespBean;
import com.erb.service.llb.InvestService;
import com.erb.service.zwj.IAdminService;
import com.erb.service.zwj.IAdminUserService;
import com.erb.service.zwj.IProductService;
import com.erb.utils.gee.GeeConfig;
import com.erb.utils.gee.GeeLib;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台公用控制器
 */
@Controller
@RequestMapping("/admin")
public class AdminPublicController {
	@Resource
	private IAdminService adminService;
	@Resource
	private IProductService productService;
	@Resource
	private IAdminUserService adminUserService;
	@Resource
	private InvestService investService;

	@GetMapping("/index")
	public String index(Model model) {
		// 查询用户总数
		model.addAttribute("userCount", adminUserService.findCount());
		// 查询项目总数
		model.addAttribute("productCount", productService.findCount(null));
		// 查询投资总笔数
		model.addAttribute("investSum", investService.sumInvest());
		// 查询项目总金额
		model.addAttribute("investCount", investService.countInvestMoney());
		return "admin/index";
	}

	@ResponseBody
	@GetMapping("/statisticsData")
	public RespBean statisticsData(Model model) {
		Map<String, Object> map = new HashMap<>(4);

		try {
			// 查询用户总数
			map.put("userCount", adminUserService.findCount());
			// 查询投资总笔数
			map.put("productCount", productService.findCount(null));
			// 查询投资总笔数
			map.put("investSum", investService.sumInvest());
			// 查询项目总金额
			map.put("investCount", investService.countInvestMoney());
		} catch (Exception e) {
			e.printStackTrace();
			map.put("userCount", 0);
			map.put("productCount", 0);
			map.put("investSum", 0);
			map.put("investCount", 0);
		}

		return RespBean.ok("查询成功！", map);
	}

	/**
	 * 后台登录页：
	 * 1.显示Cookie数据
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/login")
	public String login(HttpSession session, HttpServletRequest request, Model model) {
		// 是否已登录。
		Admin sessionAdmin = (Admin) session.getAttribute(AdminConstants.SESSION_ADMIN_KEY);
		if (null != sessionAdmin) {
			return "redirect:/admin/index";
		}

		// 获取cookie记录，用于用户名密码显示
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				// 查找管理员对象
				if (AdminConstants.COOKIE_ADMIN_KEY.equals(cookie.getName())) {
					String decode = null;
					try {
						// 解码cookie中的value（JSON字符串）
						decode = URLDecoder.decode(cookie.getValue(), AdminConstants.ADMIN_CHARSET.name());
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					if (null != decode) {// 解码成功
						// 将Cookie中的JSON字符串转换对象，并传入显示
						model.addAttribute("adminObject", JSONObject.parseObject(decode, Admin.class));
					}
				}
			}
		}

		return "admin/login";
	}

	/**
	 * 初始化后台滑块验证码
	 *
	 * @param session
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getGee")
	public String getGee(HttpSession session) {
		GeeLib geeLib = new GeeLib(GeeConfig.getGee_id(), GeeConfig.getGee_key(), GeeConfig.isnewfailback());

		//自定义参数,可选择添加
		HashMap<String, String> paramMap = new HashMap<String, String>(2);
		paramMap.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
		paramMap.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP

		// 进行一次验证，得到结果
		int result = geeLib.preProcess(paramMap);
		session.setAttribute(geeLib.gtServerStatusSessionKey, result);
		return geeLib.getResponseStr();
	}

	@ResponseBody
	@PostMapping("/login")
	public Map<String, Object> submitLoginForm(HttpSession session, HttpServletResponse response,
	                                           @RequestParam("username") String username,
	                                           @RequestParam("password") String password,
	                                           Boolean isRemember) {
		Map<String, Object> map = new HashMap<>(2);

		Admin adminObject = adminService.findAdminForLogin(username, password);
		if (null == adminObject) {
			map.put("code", 1);
			map.put("msg", "用户名或密码错误！");
		} else {
			// 登录成功，记录session
			session.setAttribute(AdminConstants.SESSION_ADMIN_KEY, adminObject);
			// 记录cookies
			if (null != isRemember && isRemember) {// 记住密码
				String path = session.getServletContext().getContextPath() + "/admin";
				int maxAge = AdminConstants.COOKIE_ADMIN_MAX_AGE;// cookie记录时间

				String encode = null;
				try {
					// 将对象编码成字符串
					encode = URLEncoder.encode(JSONObject.toJSONString(adminObject), AdminConstants.ADMIN_CHARSET.name());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				Cookie cookieAdminObject = new Cookie(AdminConstants.COOKIE_ADMIN_KEY, encode);
				cookieAdminObject.setPath(path);
				cookieAdminObject.setMaxAge(maxAge);
				response.addCookie(cookieAdminObject);
			}

			map.put("code", 0);
			map.put("msg", "登录成功！");
		}

		return map;
	}

	/**
	 * 管理员退出：清除session
	 *
	 * @return
	 */
	@GetMapping("/exit")
	public String exit(HttpSession session) {
		session.invalidate();
		return "redirect:/admin/login";
	}
}
